﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using Microsoft.Win32;
using System.Xml;
using Shell32;
using System.Text.RegularExpressions;
using System.Collections;
using System.Runtime.InteropServices;
using System.Media;


namespace music_player
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static uint SND_ASYNC = 0x0001;

        public static uint SND_FILENAME = 0x00020000;

        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        public static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
  
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetShortPathName(string lpszLongPath, string shortFile, int cchBuffer);

        private int m_PlayMillisecond = 0;
        public int PlayMillisecond { get { return m_PlayMillisecond; } }

        private int _Long = 0;

        public int vol;
        
        private int index = 0;

        private System.Windows.Threading.DispatcherTimer _MyTime=null;

        List<XmlListProduct> musiclist = new List<XmlListProduct>();

        Random indexes = new Random();
        int sum = 0;
        public MainWindow()
        {
            InitializeComponent();
            if(Properties.Settings.Default.HasStartMusic)
            {
                XmlListProduct xml = new XmlListProduct();
                xml.Url = Properties.Settings.Default.StartMusic;
                Play(xml);
            }
            musicReader mlr = new musicReader("playList.xml");  //加载播放列表的文件
            for (int i = 0; i < mlr.GetXmlCount(); i++)
            {

                XmlListProduct xlp = mlr.GetXmlMusicItemInformation(i);  //读取xml中的信息
                ListBoxItem item = new ListBoxItem();
                item.Content = xlp;
                musiclist.Add(xlp);
                sum++;
            }
            list.ItemsSource = musiclist;
            list.Items.Refresh();
        }

        private void quit_Click(object sender, RoutedEventArgs e)
        {
            mciSendString("close temp_alias", null, 0, 0);
            this.Close();
        }

        private void minsize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void play_Click(object sender, RoutedEventArgs e)
        {
            ImageBrush brush = new ImageBrush();
            string m = GetPlayMode();
            switch (m)
            {
                case "playing":
                    brush.ImageSource = new BitmapImage(new Uri("play.png", UriKind.Relative));
                    play.Background = brush;
                    mciSendString("pause temp_alias", null, 0, 0);
                    _MyTime.Stop();
                    break;
                case "paused":
                    brush.ImageSource = new BitmapImage(new Uri("pause.png", UriKind.Relative));
                    play.Background = brush;
                    mciSendString("resume temp_alias", null, 0, 0);
                    _MyTime.Start();
                    break;
                default:
                    break;
            }
            
        }

        private void sound_MouseEnter(object sender, MouseEventArgs e)
        {
            sound.Visibility = Visibility.Visible;
            soundSize.Visibility = Visibility.Visible;
            sound.Value = Volume/10;
        }

        private void sound_MouseLeave(object sender, MouseEventArgs e)
        {
            sound.Visibility = Visibility.Hidden;
            soundSize.Visibility = Visibility.Hidden;
        }

        

        private void add_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new Microsoft.Win32.OpenFileDialog();
            op.Multiselect = true;
            op.Filter = "MP3文件(*.mp3)|*.mp3";
            op.RestoreDirectory = true;
            Nullable<bool> result =op.ShowDialog();
            if (result==true)
            {
                ArrayList fileList = new ArrayList();
                foreach (string file in op.FileNames)
                {
                    string strFileName = file;
                    string dirName = System.IO.Path.GetDirectoryName(strFileName);
                    string SongName = System.IO.Path.GetFileName(strFileName);//获得歌曲名称  
                    ShellClass sh = new ShellClass();
                    Folder dir = sh.NameSpace(dirName);
                    FolderItem item = dir.ParseName(SongName);
                    string time = Regex.Match(dir.GetDetailsOf(item, -1), "\\d:\\d{2}:\\d{2}").Value;//获取歌曲时间
                    time = time.Substring(2, time.Length - 2);

                    XmlDocument doc = new XmlDocument();
                    doc.Load("playlist.xml");
                    XmlNode node = doc.SelectSingleNode("Root");

                    XmlElement xe1 = doc.CreateElement("Music");//创建一个<Music>节点
                    XmlElement xelsub = doc.CreateElement("url");
                    xelsub.InnerText = file;
                    xe1.AppendChild(xelsub);
                    XmlElement xelsub1 = doc.CreateElement("time");
                    xelsub1.InnerText = time;
                    xe1.AppendChild(xelsub1);

                    node.AppendChild(xe1);
                    doc.Save("playlist.xml");

                    XmlListProduct xml = new XmlListProduct(file, time);
                    musiclist.Add(xml);
                    sum++;
                }
                

                list.ItemsSource = null;
                list.ItemsSource = musiclist;
            }
        }

        private void ListBoxItem_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            string mode = GetPlayMode();
            var item = list.SelectedItem as XmlListProduct;
            Play(item);
            index = list.SelectedIndex;

            ImageBrush brush = new ImageBrush();
            brush.ImageSource = new BitmapImage(new Uri("pause.png", UriKind.Relative));
            play.Background = brush;
            slider.AddHandler(Slider.MouseLeftButtonUpEvent, new MouseButtonEventHandler(slider_ValudeChanged), true);
        }

        void _MyTime_Tick(object sender, EventArgs e)
        {
            int _TempPoint = PlayPoint;       //获取当前播放时间
            slider.Value = _TempPoint;
        }

      

        private void slider_ValudeChanged(object sender, MouseButtonEventArgs e)
        {
            PlayPoint = (int)slider.Value;
        }

        private void volumn_Click(object sender, RoutedEventArgs e)
        {
            ImageBrush brush = new ImageBrush();
            if (Volume!=0)
            {
                brush.ImageSource = new BitmapImage(new Uri("mute.png", UriKind.Relative));
                vol = Volume;
                Volume = 0;
            }
            else
            {
                Volume = vol;
                if(sound.Value<0.5)
                    brush.ImageSource = new BitmapImage(new Uri("smaller.png", UriKind.Relative));
                else
                    brush.ImageSource = new BitmapImage(new Uri("bigger.png", UriKind.Relative));
            }
            volumn.Background = brush;
        }

        private void sound_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            ImageBrush brush = new ImageBrush();
            Volume = (int)sound.Value*10;
            if(sound.Value==0)
            {
                brush.ImageSource = new BitmapImage(new Uri("mute.png", UriKind.Relative));
                volumn.Background = brush;
            }
            else if(sound.Value<50)
            {
                brush.ImageSource = new BitmapImage(new Uri("smaller.png", UriKind.Relative));
                volumn.Background = brush;
            }
            else
            {
                brush.ImageSource = new BitmapImage(new Uri("bigger.png", UriKind.Relative));
                volumn.Background = brush;
            }
        }

        private void setting_Click(object sender, RoutedEventArgs e)
        {
            settings settingWindow = new settings();
            settingWindow.Show();
        }

        private void next_Click(object sender, RoutedEventArgs e)
        {
            XmlListProduct item=new XmlListProduct();
            switch (Properties.Settings.Default.Mode)
            {
                case 0:
                    item = list.Items[index] as XmlListProduct;
                    break;
                case 1:
                    index++;
                    if (index == sum) index = 0;
                    item = list.Items[index] as XmlListProduct;
                    break;
                case 2:
                    index = (int)indexes.Next(0, sum);
                    item = list.Items[index] as XmlListProduct;
                    break;
            }
            Play(item);
        }

        private void previous_Click(object sender, RoutedEventArgs e)
        {
            XmlListProduct item = new XmlListProduct();
            switch (Properties.Settings.Default.Mode)
            {
                case 0:
                    item = list.Items[index] as XmlListProduct;
                    break;
                case 1:
                    index--;
                    if (index < 0) index = sum-1;
                    item = list.Items[index] as XmlListProduct;
                    break;
                case 2:
                    index = (int)indexes.Next(0, sum);
                    item = list.Items[index] as XmlListProduct;
                    break;
            }
            Play(item);
        }

        private void table_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.Mode = 1;
        }

        private void random_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.Mode = 2;
        }

        private void repeat_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.Mode = 0;
        }

        private string GetPlayMode()
        {
            string _Temp = "".PadLeft(128, ' ');
            mciSendString("status temp_alias mode", _Temp, 128, 0);
            return _Temp.Trim().Remove(_Temp.Trim().Length - 1, 1);
        }

        public int Volume
        {
            get
            {
                string _Temp = "".PadLeft(128, ' ');
                mciSendString("status temp_alias volume", _Temp, 128, 0);
                _Temp = _Temp.Trim().Remove(_Temp.Trim().Length - 1, 1);
                if (_Temp.Length == 0) return 0;
                return Int32.Parse(_Temp);

            }
            set
            {
                string _Temp = "".PadLeft(128, ' ');
                mciSendString("setaudio temp_alias volume to " + value.ToString(), _Temp, 128, 0);
            }
        }

        public int PlayPoint
        {
            get
            {
                string _Temp = "".PadLeft(128, ' ');
                int TTT = mciSendString("status temp_alias position", _Temp, 128, 0);
                _Temp = _Temp.Trim();
                _Temp = _Temp.Substring(0, _Temp.Length - 1);
                if (_Temp.Length == 0) return 0;
                return Int32.Parse(_Temp)/1000;
            }
            set
            {
                if (value > m_PlayMillisecond) return;
                string _Temp = "".PadLeft(128, ' ');
                string _PlayType = GetPlayMode();             //获取播放类型  
                _Long = mciSendString("Seek temp_alias to " + (value*1000).ToString(), _Temp, 128, 0); //暂停文件  //移动到那里
                switch (_PlayType)
                {
                    case "playing":
                        _Long = mciSendString("play temp_alias", _Temp, 128, 0); //继续播放文件 
                        break;
                    default:
                        break;
                }
            }
        }
        public void Play(XmlListProduct xml)
        {
            string mode = GetPlayMode();
            if (mode.Equals("playing")) _MyTime.Stop();
            else
            {
                _MyTime = new System.Windows.Threading.DispatcherTimer();
                _MyTime.Interval = new TimeSpan(0, 0, 1);
                _MyTime.Tick += _MyTime_Tick;
            }
            string aa = "open \"" + xml.Url + "\" alias temp_alias";
            mciSendString(@"close temp_alias", null, 0, 0);
            mciSendString(aa, null, 0, 0);
            mciSendString("play temp_alias", null, 0, 0);
            string _temp = "".PadLeft(128, ' ');
            mciSendString("status temp_alias length", _temp, 128, 0);
            _temp = _temp.Trim();
            _temp = _temp.Substring(0, _temp.Length - 1);
            m_PlayMillisecond = Int32.Parse(_temp) / 1000;
            _MyTime.Start();
            slider.Maximum = PlayMillisecond;
            currentMusicName.Content = "正在播放 " + xml.Name;
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.DragMove();
        }
    }
}
